#include "EyerWASMIndexedDB_OpenEvent.hpp"

#include <emscripten.h>
#include <stdio.h>

extern "C"
{
    EMSCRIPTEN_KEEPALIVE int EyerWASMIndexedDB_OpenEvent_Open(void * ctx, const char * dbName);

    EMSCRIPTEN_KEEPALIVE int EyerWASMIndexedDB_OpenEvent_Open_OnSucc(void * ctx, int key)
    {
        Eyer::EyerWASMIndexedDB_OpenEvent * event = (Eyer::EyerWASMIndexedDB_OpenEvent *)ctx;
        return event->EyerWASMIndexedDB_OpenEvent_Open_OnSucc(key);
    }

    EMSCRIPTEN_KEEPALIVE int EyerWASMIndexedDB_OpenEvent_Open_OnFail(void * ctx)
    {
        Eyer::EyerWASMIndexedDB_OpenEvent * event = (Eyer::EyerWASMIndexedDB_OpenEvent *)ctx;
        return event->EyerWASMIndexedDB_OpenEvent_Open_OnFail();
    }
}

namespace Eyer
{
    EyerWASMIndexedDB_OpenEvent::EyerWASMIndexedDB_OpenEvent(const std::string & _dbName)
        : dbName(_dbName)
    {

    }

    int EyerWASMIndexedDB_OpenEvent::Run()
    {
        std::unique_lock<std::mutex> lck(mtx);
        EyerWASMIndexedDB_OpenEvent_Open(this, dbName.c_str());
        return 0;
    }

    int EyerWASMIndexedDB_OpenEvent::EyerWASMIndexedDB_OpenEvent_Open_OnSucc(int key)
    {
        std::unique_lock<std::mutex> lck(mtx);
        m_indexedDBKey = key;
        isSucced = true;
        isFinished = true;
        cond.notify_all();
        return 0;
    }

    int EyerWASMIndexedDB_OpenEvent::EyerWASMIndexedDB_OpenEvent_Open_OnFail()
    {
        std::unique_lock<std::mutex> lck(mtx);
        isSucced = false;
        isFinished = true;
        cond.notify_all();
        return 0;
    }

    int EyerWASMIndexedDB_OpenEvent::GetIndexedDBKey()
    {
        return m_indexedDBKey;
    }
}